import base64
import json
import os
import urllib.parse

from bs4 import BeautifulSoup
from django.db import connection
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.core.paginator import Paginator, PageNotAnInteger
from django.db.models import Q
import datetime, time
from dateutil.relativedelta import relativedelta
from administrative.models import Company, OfficialDocuments, Topicsattachments
from back_management.models import *
from finance.models import OutgoingCadresData, TravelReimbursement, LeaveRequest
from forum import search_echart_data
from forum.forms import ContentForm
from forum.models import Article, Category, ArticleComment
from personal_center.PrintingStatistics import SummaryApprovalDocuments
from personal_center.models import User, SealApply



def str_to_timestamp(date_str, date_format):
    date_struct = time.strptime(date_str, date_format)
    timestamp = time.mktime(date_struct)
    return timestamp


def article(request):
    if request.method == 'GET':  # 获取空界面用于创建该文章的内容
        try:
            realname = request.user.real_name
        except:
            return redirect("/")
        categorys = Category.objects.all()
        context = {
            'content_form': ContentForm(),
            'realname': request.user.real_name,
            'position': request.user.post,
            'categorys': categorys,
        }
        return render(request, 'forum/article.html', context=context)

    if request.method == 'POST':  # 新建文章
        title = request.POST.get('title', None)
        content_html = request.POST.get('content_html', None)
        content_text = BeautifulSoup(content_html, features="html.parser").text
        # print(content_text)
        category = request.POST.get('category', None)
        if category:
            category_objs = Category.objects.filter(name=category)
            if category_objs.count() > 0:
                category_obj = category_objs.first()
            else:
                category_obj = Category.objects.create(name=category)
        else:
            returnDict = {'code': 200, 'message': '分类不能为空！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        Article.objects.create(title=title, content_html=content_html, author=request.user, category_id=category_obj.id,
                               content_text=content_text)

        return redirect('/forum/forum_home')


class ForumHome(View):
    # 论坛首页
    def get(self, request):
        category = request.GET.get('category', None)
        search_value = request.GET.get("search_value", None)
        category_list = Category.objects.all().order_by('-name')
        if search_value:
            objs = Article.objects.all().order_by('-create_time')
        else:
            objs = Article.objects.all().order_by('-create_time')

        if category:
            objs = Article.objects.all().filter(category_id=category)

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)
        # objs.previous_page_number
        # objs_list = [{'id': obj.id, 'title': obj.title} for obj in objs_list]
        sql = '''
        SELECT
            b.real_name, b.id
            from (SELECT
            a.author_id as author_id,
            count(a.author_id) as number
            FROM forum_article a GROUP BY a.author_id) a
            left join tb_users_message b on a.author_id = b.id ORDER BY a.number DESC limit 10
        
        '''
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()

        name_list = []
        for row in rows:
            name_list.append({'name': row[0], "user_id": row[1]})
        # print(name_list)
        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value,
                   "name_list": name_list,
                   'category_list': category_list
                   }
        if not search_value:
            context.pop("search_value")
        return render(request, 'forum/forum_total_page.html', context)


class ForumDetails(View):
    # 帖子详情页
    def get(self, request):
        id = request.GET.get('id', None)
        obj = Article.objects.get(id=id)
        if request.user not in obj.see_users.all():
            obj.see_users.add(request.user)
        # comment_records = [
        #     {'comment_text': urllib.parse.unquote(base64.b64decode(
        #         articlecomment.comment_text).decode()),
        #      "comment_user": articlecomment.comment_user.real_name + '(作者)' if obj.author == articlecomment.comment_user else articlecomment.comment_user.real_name,
        #      "respondent": articlecomment.respondent.real_name + '(作者)' if obj.author == articlecomment.respondent else articlecomment.respondent.real_name,
        #      "create_time": articlecomment.create_time.strftime("%Y-%m-%d %H:%M"),
        #      "id": articlecomment.id
        #      } for
        #     articlecomment in obj.articlecomment_set.filter(parent_id=None)]

        comment_records = []
        for articlecomment in obj.articlecomment_set.filter(parent_id=None):
            comment_records.append(
                {"parent": {
                    'comment_text': urllib.parse.unquote(base64.b64decode(articlecomment.comment_text).decode()),
                    "comment_user": articlecomment.comment_user.real_name + '(作者)' if obj.author == articlecomment.comment_user else articlecomment.comment_user.real_name,
                    "respondent": articlecomment.respondent.real_name + '(作者)' if obj.author == articlecomment.respondent else articlecomment.respondent.real_name,
                    "create_time": articlecomment.create_time.strftime("%Y-%m-%d %H:%M"),
                    "id": articlecomment.id,
                    "comment_user_id": articlecomment.comment_user.id,
                },
                    "son": [{
                        'comment_text': urllib.parse.unquote(base64.b64decode(son_obj.comment_text).decode()),
                        "comment_user": son_obj.comment_user.real_name + '(作者)' if obj.author == son_obj.comment_user else son_obj.comment_user.real_name,
                        "respondent": son_obj.respondent.real_name + '(作者)' if obj.author == son_obj.respondent else son_obj.respondent.real_name,
                        "create_time": son_obj.create_time.strftime("%Y-%m-%d %H:%M"),
                        "id": son_obj.id,
                        "comment_user_id": son_obj.comment_user.id,
                        "parent_id": articlecomment.id
                    } for
                        son_obj in obj.articlecomment_set.filter(parent_id=articlecomment.id)]
                }
            )
        print(comment_records)
        context = {
            'obj': obj,
            'realname': request.user.real_name, 'position': request.user.post,
            'is_like': 'true' if request.user in obj.like_users.all() else 'false',
            'is_collection': 'true' if request.user in obj.collection_users.all() else 'false',
            'comment_records': comment_records
        }
        return render(request, 'forum/forum_details_page.html', context)


class ForumLikeView(View):
    def get(self, request):
        user = request.user
        objs = user.article_like_users.all()
        context = {'objs': objs, 'realname': request.user.real_name, 'position': request.user.post}
        # 此处改为我的点赞页面
        return render(request, 'forum/forum_my_like.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        obj = Article.objects.get(id=id)
        if request.user not in obj.like_users.all():
            obj.like_users.add(request.user)
            mesg = '点赞成功'
        else:
            obj.like_users.remove(request.user)
            mesg = '取消点赞'
        returnDict = {'code': 200, 'message': mesg}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ForumCollectionView(View):
    def get(self, request):
        user = request.user
        objs = user.article_collection_users.all()
        context = {'objs': objs, 'realname': request.user.real_name, 'position': request.user.post}
        # 此处改为我的收藏页面
        return render(request, 'forum/forum_my_collect.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        obj = Article.objects.get(id=id)
        if request.user not in obj.collection_users.all():
            obj.collection_users.add(request.user)
            mesg = '收藏成功'
        else:
            obj.collection_users.remove(request.user)
            mesg = '取消收藏'
        returnDict = {'code': 200, 'message': mesg}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ForumCommentView(View):
    def post(self, request):
        article_id = request.POST.get('article_id', None)
        parent_id = request.POST.get('parent_id', None)
        respondent = request.POST.get('respondent', None)
        comment_text = request.POST.get('comment_text', None)
        if parent_id and parent_id != 'null':
            parent_id = int(parent_id)
        else:
            parent_id = None

        if respondent and respondent != 'null':
            respondent_id = int(respondent)
        else:
            article_obj = Article.objects.get(id=int(article_id))
            respondent_id = article_obj.author.id
        ArticleComment.objects.create(comment_user=request.user, article_id=article_id, comment_text=comment_text,
                                      respondent_id=respondent_id, parent_id_id=parent_id)
        returnDict = {'code': 200, 'message': '评论成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ForumReleaseView(View):
    def get(self, request):
        user = request.user
        objs = user.article_set.all()
        context = {'objs': objs, 'realname': request.user.real_name, 'position': request.user.post}
        # 此处改为我的发布页面
        return render(request, 'forum/forum_my_upload.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        obj = Article.objects.get(id=id)
        obj.delete()
        returnDict = {'code': 200, 'message': '删除成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class CreatorCenter(View):
    def get(self, request):
        rank = request.GET.get("rank", None)
        user_id = request.GET.get("user_id", None)
        user_obj = User.objects.get(id=int(user_id))
        objs = user_obj.article_set.all()
        like_num = sum([obj.like_users.all().count() for obj in objs])
        comment_num = sum([obj.articlecomment_set.all().count() for obj in objs])
        head_portrait = str(user_obj.head_portrait)
        context = {"objs": objs, 'realname': request.user.real_name, 'position': request.user.post,
                   'user_obj': user_obj, "like_num": like_num, "comment_num": comment_num, "rank": rank, "head_portrait": head_portrait}
        return render(request, "forum/creator_center.html", context)


class ForumPopularView(View):
    def get(self, request):
        sql = '''
        select 
        a.id as id,
        a.create_time as create_time,
        author.real_name as author,
        a.title as title,
        a.content_text as content_text,
        IFNULL(li.number,0) as number
        from forum_article a
        left join tb_users_message author on author.id = a.author_id
        left join (SELECT l.article_id as article_id, count(l.article_id) as number FROM forum_article_like_users l GROUP BY l.article_id) li on li.article_id = a.id
        ORDER BY number DESC
        '''
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
        record_list = []
        for row in rows:
            record_list.append({
                'id': row[0],
                'create_time': row[1].strftime("%Y-%m-%d %H:%M"),
                'author': row[2],
                'title': row[3],
                'content_text': row[4],
                'number': row[5],
            })
        context = {'record_list': record_list, 'realname': request.user.real_name, 'position': request.user.post}
        # 此处改为热门页面
        return render(request, 'forum/forum_competitive.html', context)


class ForumWatchedView(View):
    def get(self, request):
        sql = '''
        select 
        a.id as id,
        a.create_time as create_time,
        author.real_name as author,
        a.title as title,
        a.content_text as content_text,
        IFNULL(li.number,0) as number
        from forum_article a
        left join tb_users_message author on author.id = a.author_id
        left join (SELECT l.article_id as article_id, count(l.article_id) as number FROM forum_article_see_users l GROUP BY l.article_id) li on li.article_id = a.id
        ORDER BY number DESC
        '''
        with connection.cursor() as cursor:
            cursor.execute(sql)
            rows = cursor.fetchall()
        record_list = []
        for row in rows:
            record_list.append({
                'id': row[0],
                'create_time': row[1].strftime("%Y-%m-%d %H:%M"),
                'author': row[2],
                'title': row[3],
                'content_text': row[4],
                'number': row[5],
            })
        context = {'record_list': record_list, 'realname': request.user.real_name, 'position': request.user.post}
        # 此处改为精品页面
        return render(request, 'forum/hot_page_show.html', context)


# 用印报表
class print_report(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        dept_id, dept = '请选择科室', '请选择科室'
        dep_dict_list = []
        all_com = Company.objects.all()
        for i in all_com:
            dep_dict_list.append({'value': i.id, 'name': i.name})
        return render(request, 'forum/print_report.html', {'realname': real_name, 'position': position, 'department': department, 'dept_id': dept_id, 'dept': dept, "dep_dict_list": dep_dict_list})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        seal_type = request.POST.get("seal_type", '')
        search_data = request.POST.get("search_data", '')  # 查询标题
        startTime = request.POST.get("startTime", '')
        endTime = request.POST.get("endTime", '')
        search_dept = request.POST.get("search_dept", '')
        category = int(request.POST.get("category", '0'))
        affix = request.POST.get("affix", '')
        offline_printing = request.POST.get("offline_printing", '0')
        if search_dept == '请选择科室':
            search_dept = ''

        if affix == '0':
            affix = ''
        if startTime:
            startTime = startTime + " 00:00:00"
            endTime = endTime + " 23:59:59"
        # 只有时间
        if startTime and not search_dept and not category and not affix and not seal_type:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), state='five', offline_printing=offline_printing).order_by('-number')

            for ii in objs_list:
                record_obj = ii.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(ii)

        # 只有部门
        elif search_dept and not startTime and not category and not affix and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            objs = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) |
                                            Q(apply_user__real_name__contains=search_data), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')

        # 只有文件类别
        elif category and not startTime and not search_dept and not affix and not seal_type:
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 只有用印类型
        elif affix and not startTime and not category and not search_dept and not seal_type:
            objs = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) |
                                            Q(apply_user__real_name__contains=search_data), is_fast= True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')

        # 只有印章名称
        elif seal_type and not affix and not startTime and not category and not search_dept:
            objs = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                                            Q(seal_name__contains=seal_type), state='five', offline_printing=offline_printing).order_by('-number')

        # 只有时间&部门
        elif startTime and search_dept and not category and not affix and not seal_type:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            com_obj = Company.objects.get(id=search_dept)
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for ii in objs_list:
                record_obj = ii.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(ii)

        # 只有时间&文件类别
        elif startTime and category and not search_dept and not affix and not seal_type:
            print("+++++++++++++++++++++++++++++++")
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 只有时间&用印类型
        elif startTime and affix and not search_dept and not category and not seal_type:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) |
                                                 Q(apply_user__real_name__contains=search_data), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(i)

        # 只有时间&印章名称
        elif startTime and seal_type and not search_dept and not category and not affix:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) |
                Q(apply_user__real_name__contains=search_data), Q(seal_name__contains=seal_type), state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(i)

        # 只有部门&文件类别
        elif search_dept and category and not startTime and not affix and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 只有部门&用印类型
        elif search_dept and affix and not startTime and not category and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            objs = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')

        # 只有部门&印章名称
        elif search_dept and seal_type and not startTime and not category and not affix:
            com_obj = Company.objects.get(id=search_dept)
            objs = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')

        # 只有文件类别&用印类型
        elif category and affix and not startTime and not search_dept and not seal_type:
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(
                    matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 只有文件类别&印章名称
        elif category and seal_type and not startTime and not search_dept and not affix:
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 只有用印类别&印章名称
        elif affix and seal_type and not startTime and not search_dept and not category:
            objs = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')

        # 时间&部门&文件类型
        elif startTime and search_dept and category and not affix and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 时间&部门&用印类型
        elif startTime and search_dept and affix and not category and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), is_fast=True if affix == '1' else False,
                apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(i)

        # 时间&部门&印章名称
        elif startTime and search_dept and seal_type and not category and not affix:
            com_obj = Company.objects.get(id=search_dept)
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            print("===========================================================================")
            print(start_date_object)
            print(end_date_object)
            objs = [end_date_object]
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(i)

        # 时间&文件类型&用印类型
        elif startTime and affix and category and not search_dept and not seal_type:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 时间&文件类型&印章名称
        elif startTime and category and seal_type and not affix and not search_dept:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(
                    matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data), Q(seal_name__contains=seal_type), state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 时间&用印类别&印章名称
        elif startTime and affix and seal_type and not category and not search_dept:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    objs.append(i)

        # 部门&文件类型&用印类型
        elif search_dept and affix and category and not startTime and not seal_type:
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 部门&文件类型&印章名称
        elif search_dept and category and seal_type and not affix and not startTime:
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 部门&用印类型&印章名称
        elif search_dept and affix and seal_type and not category and not startTime:
            com_obj = Company.objects.get(id=search_dept)
            objs = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')

        # 文件类型&用印类型&印章名称
        elif category and affix and seal_type and not search_dept and not startTime:
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 时间&部门&文件类别&用印类别
        elif startTime and search_dept and category and affix and not seal_type:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 时间&部门&文件类别&印章名称
        elif startTime and search_dept and category and seal_type and not affix:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 时间&文件类别&用印类别&印章名称
        elif startTime and category and affix and seal_type and not search_dept:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        # 部门&文件类别&用印类别&印章名称
        elif search_dept and category and affix and seal_type and not startTime:
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                if category == 1:
                    if roced_count:
                        objs.append(i)
                else:
                    if not roced_count:
                        objs.append(i)

        # 全部都有
        elif startTime and category and affix and seal_type and search_dept:
            start_date_object = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
            end_date_object = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
            com_obj = Company.objects.get(id=search_dept)
            objs = []
            objs_list = SealApply.objects.filter(
                Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) | Q(apply_user__real_name__contains=search_data),
                Q(seal_name__contains=seal_type), apply_user__company=com_obj, is_fast=True if affix == '1' else False, state='five', offline_printing=offline_printing).order_by('-number')
            for i in objs_list:
                roced_count = i.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')).count()
                record_obj = i.sealapplyauditrecord_set.all().order_by("update_time").last()
                if record_obj.update_time >= start_date_object and record_obj.update_time <= end_date_object:
                    if category == 1:
                        if roced_count:
                            objs.append(i)
                    else:
                        if not roced_count:
                            objs.append(i)

        else:
            objs = SealApply.objects.filter(Q(number__contains=search_data) | Q(servings__contains=search_data) | Q(matter_type_text__contains=search_data) |
                                     Q(apply_user__real_name__contains=search_data), state='five', offline_printing=offline_printing).order_by('-number')

        data_list = [
            {'id': obj.id,
             'number': obj.number,
             'date': obj.create_time.strftime("%m.%d"),
             'matter_type_text': f'<a href="/personal-center/seal_apply_detail_view?id={obj.id}" target="_blank">{obj.matter_type_text}</a>',
             'company': obj.apply_user.company.name, 'apply_user': obj.apply_user.real_name, 'servings': obj.servings,
             'agreement': '协议类' if obj.sealapplyauditrecord_set.filter(Q(node='sjk') | Q(node='audits')) else "非协议类",
             'note': obj.note+'&&'+obj.sealapplyauditrecord_set.all().order_by('update_time').last().audit_note if obj.sealapplyauditrecord_set.all().order_by('update_time').last().audit_note else obj.note,
             'director': obj.apply_user.company.head_people.real_name,
             'leader': obj.sealapplyauditrecord_set.filter(node='B').last().audit_people.real_name if obj.sealapplyauditrecord_set.filter(node='B').count() else ''} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": len(objs), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 用印报表 图表
class print_report_echart(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        days = request.GET.get("days", None)
        if days:
            datetime_now = datetime.datetime.now()
            if days == 'week':
                datetime_ago = (datetime_now - relativedelta(days=7)).strftime("%Y-%m-%d")
            elif days == 'LastMonth':
                datetime_ago = (datetime_now - relativedelta(month=1)).strftime("%Y-%m-%d")
            elif days == 'LastThreeMonths':
                datetime_ago = (datetime_now - relativedelta(month=3)).strftime("%Y-%m-%d")
            else:
                datetime_ago = (datetime_now - relativedelta(month=6)).strftime("%Y-%m-%d")
            yf_list, data_list, dep_list, dep_number_list = search_echart_data.search_data().search_seal(datetime_ago)
        else:
            yf_list, data_list, dep_list, dep_number_list = search_echart_data.search_data().search_seal()
        return render(request, 'forum/print_report_echart.html', {'realname': real_name, 'position': position, 'department': department, "yf_list": yf_list, "data_list": data_list, "dep_list": dep_list, "dep_number_list": dep_number_list})

# 中层干部外出报表
class middle_level_echart(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'forum/middle_level_echart.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_data = request.POST.get("search_data", '')  # 查询标题
        search_time = request.POST.get("test08", '')  # 查询外出时间
        if search_time:
            objs = OutgoingCadresData.objects.filter(Q(title__contains=search_data) | Q(destination__contains=search_data), create_time__range=(search_time.split(' 至 ')[0], search_time.split(' 至 ')[1]), state='seven').order_by('-create_time')
        else:
            objs = OutgoingCadresData.objects.filter(Q(title__contains=search_data) | Q(destination__contains=search_data), state='seven').order_by('-create_time')

        data_list = [
            {'id': obj.id,
             'outsiders': ", ".join([i.real_name for i in obj.outgoing_person.all()]),
             'leader': obj.company.leaders_id.real_name,
             "apply_time": obj.create_time.strftime("%Y-%m-%d"),
             'duties': obj.duties,
             'outgoing_time': '.'.join(obj.start_time.split('-')[1:]) + '-' + '.'.join(obj.end_time.split('-')[1:]),
             'title': f'<a href="/finance/middle_level_detail.html?id={obj.id}">{obj.title}</a>',
             'destination': obj.destination,
             'apply_user': obj.apply_user.real_name,
             'department_charge': obj.department_charge.director_id.real_name if obj.department_charge else ""} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 上级来文报表
class SuperiorOfficial(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'forum/superior_official.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_data = request.POST.get("search_data", '')  # 查询标题
        startTime = request.POST.get("startTime", '')  # 查询外出时间
        endTime = request.POST.get("endTime", '')  # 查询外出时间
        flow_name = request.POST.get("flow_name", '')

        if flow_name:
            type_list = ['d'] if flow_name == "1" else ["e"]
        else:
            type_list = ["d", "e"]

        if startTime:
            objs = OfficialDocuments.objects.filter(Q(title__contains=search_data) | Q(content__contains=search_data) | Q(recive_number__contains=search_data), create_time__range=(startTime, endTime), type__in=type_list).order_by('-create_time')
        else:
            objs = OfficialDocuments.objects.filter(Q(title__contains=search_data) | Q(content__contains=search_data) | Q(recive_number__contains=search_data), type__in=type_list).order_by('-create_time')
        data_list = []

        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            try:
                data_list.append({'id': obj.id, 'recive_number': obj.recive_number, 'send_company': obj.send_company,
                                  "create_time": obj.create_time.strftime("%m.%d"), 'send_number': obj.send_number,
                                  'title': f'<a href="/personal-center/examinationDetail.html?id={obj.id}">{obj.title}</a>',
                                  'ReviewLeaders': obj.officialdocumentsauditrecord_set.filter(node='B').last().audit_people.real_name if obj.officialdocumentsauditrecord_set.filter(node='B') else obj.officialdocumentsauditrecord_set.filter(node='two').last().audit_people.real_name,
                                  'ReviewComments': obj.officialdocumentsauditrecord_set.filter(node='B').last().audit_note if obj.officialdocumentsauditrecord_set.filter(node='B') else obj.officialdocumentsauditrecord_set.filter(node='two').last().audit_note})
            except:
                try:
                    data_list.append({'id': obj.id, 'recive_number': obj.recive_number, 'send_company': obj.send_company,
                                      "create_time": obj.create_time.strftime("%m.%d"), 'send_number': obj.send_number,
                                      'title': f'<a href="/personal-center/examinationDetail.html?id={obj.id}">{obj.title}</a>',
                                      'ReviewLeaders': obj.officialdocumentsauditrecord_set.filter(node='YZ/SJ').last().audit_people.real_name,
                                      'ReviewComments': obj.officialdocumentsauditrecord_set.filter(node='YZ/SJ').last().audit_note
                                      })
                except:
                    data_list.append(
                        {'id': obj.id, 'recive_number': obj.recive_number, 'send_company': obj.send_company,
                         "create_time": obj.create_time.strftime("%m.%d"), 'send_number': obj.send_number,
                         'title': f'<a href="/personal-center/examinationDetail.html?id={obj.id}">{obj.title}</a>',
                         'ReviewLeaders': '',
                         'ReviewComments': ''
                         })
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TravelReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'forum/TravelReport.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_data = request.POST.get("search_data", '')       # 查询标题
        startTime = request.POST.get("startTime", '')       # 查询外出开始时间
        endTime = request.POST.get("endTime", '')       # 查询外出结束时间
        funding_type = request.POST.get("funding_type", '0')     # 查询经费类型
        if startTime and funding_type != "0":
            objs = TravelReimbursement.objects.filter(Q(business_matter__contains=search_data) | Q(business_days__contains=search_data) | Q(total__contains=search_data) | Q(payee__contains=search_data) | Q(company__name__contains=search_data) | Q(applicat__real_name__contains=search_data), create_time__range=(startTime, endTime), state="seven", SourceFunds=funding_type).order_by('-create_time')
        elif startTime and funding_type == "0":
            objs = TravelReimbursement.objects.filter(Q(business_matter__contains=search_data) | Q(business_days__contains=search_data) | Q(total__contains=search_data) | Q(payee__contains=search_data) | Q(company__name__contains=search_data) | Q(applicat__real_name__contains=search_data), create_time__range=(startTime, endTime), state="seven").order_by('-create_time')
        elif not startTime and funding_type != "0":
            objs = TravelReimbursement.objects.filter(Q(business_matter__contains=search_data) | Q(business_days__contains=search_data) | Q(total__contains=search_data) | Q(payee__contains=search_data) | Q(company__name__contains=search_data) | Q(applicat__real_name__contains=search_data), SourceFunds=funding_type, state="seven").order_by('-create_time')
        else:
            objs = TravelReimbursement.objects.filter(Q(business_matter__contains=search_data) | Q(business_days__contains=search_data) | Q(total__contains=search_data) | Q(payee__contains=search_data) | Q(company__name__contains=search_data) | Q(applicat__real_name__contains=search_data), state="seven").order_by('-create_time')
        data_list = []

        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            data_list.append({'id': obj.id, 'business_matter': f'<a href="/personal-center/examinationDetail.html?id={obj.id}">{obj.business_matter}</a>', 'applicat': obj.applicat.real_name,
                              "create_time": obj.create_time.strftime("%Y-%m-%d"), 'company': obj.company.name,
                              'total': obj.total,
                              'SourceFunds': "学科经费" if obj.SourceFunds == "1" else "公卫经费" if obj.SourceFunds == "2" else "自有经费",
                              'payee': obj.payee})

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class LeaveReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        leave_li = {'a': '年休假', 'b': '婚假', 'c': '丧假', 'd': '事假', 'e': '病假', 'f': '探亲假', 'g': '放射假', 'h': '产假', 'i': '计生假', 'j': '育儿假'}
        objs = LeaveRequest.objects.filter(state="seven").values("leave_type").distinct()
        leave_list = []
        for i in objs:
            leave_list.append({"type": i['leave_type'], "value": leave_li[i['leave_type']]})
        return render(request, 'forum/LeaveReport.html', {'realname': real_name, 'position': position, 'department': department, "dep_dict_list": leave_list})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_data = request.POST.get("search_data", '')       # 查询标题
        startTime = request.POST.get("startTime", '至')       # 查询外出时间
        endTime = request.POST.get("endTime", '至')  # 查询外出时间
        search_dept = request.POST.get("search_dept", '0')     # 查询经费类型

        if search_data and not startTime and search_dept == "0":
            objs = LeaveRequest.objects.filter(Q(reason__contains=search_data) | Q(apply_user__real_name__contains=search_data), state="seven").order_by('-create_time')
        elif search_data and startTime and not search_dept == "0":
            objs = LeaveRequest.objects.filter(Q(reason__contains=search_data) | Q(apply_user__real_name__contains=search_data), state="seven", end_time__range=[startTime, endTime]).order_by('-create_time')
        elif search_data and not startTime and search_dept != "0":
            objs = LeaveRequest.objects.filter(Q(reason__contains=search_data) | Q(apply_user__real_name__contains=search_data), state="seven", leave_type=search_dept).order_by('-create_time')
        elif startTime and not search_data and search_dept == "0":
            objs = LeaveRequest.objects.filter(state="seven", end_time__range=[startTime, endTime]).order_by('-create_time')
        elif startTime and search_dept != "0" and not search_data:
            objs = LeaveRequest.objects.filter(state="seven", end_time__range=[startTime, endTime], leave_type=search_dept).order_by('-create_time')
        elif search_data and startTime and search_dept != "0":
            objs = LeaveRequest.objects.filter(Q(reason__contains=search_data) | Q(apply_user__real_name__contains=search_data), state="seven", end_time__range=[startTime, endTime], leave_type=search_dept).order_by('-create_time')
        else:
            objs = LeaveRequest.objects.filter(state="seven").order_by('-create_time')

        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            amount = (datetime.strptime(obj.end_time, '%Y-%m-%d') - datetime.strptime(obj.start_time, '%Y-%m-%d')).days+1 if "待定" not in obj.start_time and "待定" not in obj.end_time else "待定"
            data_list.append({'id': obj.id, 'business_matter': f'<a href="/personal-center/leave_request_detail_view?id={obj.id}">{obj.reason if obj.reason else obj.get_leave_type()}</a>', 'applicat': obj.apply_user.real_name, "seniority": "", "amount": amount,
                              "job_number": obj.apply_user.job_number, "role": obj.apply_user.role, "leave_type": obj.get_leave_type(), 'company': obj.company.name, "start_time": obj.start_time, "end_time": obj.end_time, })

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class OfficialDocumentReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, 'forum/OfficialDocumentReport.html', {'realname': real_name, 'position': position, 'department': department})

class VotingManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        objs = request.user.votingpeopletable_set.all().order_by("-create_time")
        data_list, flow_id = [], ""
        background_flag = False
        for obj in objs:
            flag, new_flag = False, True
            now_timestamp = int(time.time())
            end_timestamp = int(str_to_timestamp(obj.voting_id.vote_deadline, '%Y-%m-%d'))
            if (now_timestamp-end_timestamp) > 0:
                new_flag = False
            else:
                if not obj.voting_option.all().count() and not background_flag:
                    flag, flow_id = True, obj.voting_id.id
                    background_flag = True
                if obj.voting_option.all().count():
                    new_flag = False
            data_list.append({"id": obj.voting_id.id, "vote_title": obj.voting_id.vote_title, "flag": flag, "new_flag": new_flag})

        if flow_id:
            flow_obj = VotingMasterTable.objects.get(id=flow_id)
        else:
            if objs:
                flow_obj = request.user.votingpeopletable_set.all().first().voting_id
                data_list[0]["flag"] = True
            else:
                flow_obj = None

        # 查看是否已经投票
        MyVotingObj = flow_obj.votingpeopletable_set.get(apply_user=request.user) if flow_obj else None
        if MyVotingObj and MyVotingObj.voting_option.all().count():
            voting_flag = "false"
            option_obj = MyVotingObj.voting_option.all().first().option
        else:
            if flow_obj:
                now_timestamp = int(time.time())
                end_timestamp = int(str_to_timestamp(flow_obj.vote_deadline, '%Y-%m-%d'))
                if (now_timestamp - end_timestamp) > 0:
                    voting_flag = "false"
                else:
                    voting_flag = 'true'
            else:
                voting_flag = 'true'
            option_obj = ''
        legend_pie = []
        if flow_obj:
            OptionObj = flow_obj.votingoptiontable_set.all()
            legend_pie = [{"value": VotingPeopleTable.objects.filter(voting_option=OptionObj[option]).count(), "name": OptionObj[option].option} for option in range(len(OptionObj))]
        return render(request, 'forum/VotingManagement.html', {'realname': real_name, 'position': position, 'department': department, "objs": data_list, "flow_obj": flow_obj,
               "VotingOption": flow_obj.votingoptiontable_set.all() if flow_obj else None, "voting_flag": voting_flag, "option_obj": option_obj,
               "end_timestamp": int(str_to_timestamp(flow_obj.vote_deadline, '%Y-%m-%d')) if flow_obj else "false", "legend_pie": legend_pie})

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        flow_obj = VotingMasterTable.objects.get(id=flow_id)
        my_voting = flow_obj.votingpeopletable_set.filter(apply_user=request.user).first()
        OptionObj = flow_obj.votingoptiontable_set.all()
        VotingOption = [{"option": i.option, "id": i.id} for i in OptionObj]
        legend_pie = [{"value": VotingPeopleTable.objects.filter(voting_option=OptionObj[option]).count(),
                       "name": OptionObj[option].option} for option in range(len(OptionObj))]
        vote_content = flow_obj.vote_content

        now_timestamp = int(time.time())
        end_timestamp = int(str_to_timestamp(flow_obj.vote_deadline, '%Y-%m-%d'))

        # 查看是否已经投票
        MyVotingObj = flow_obj.votingpeopletable_set.get(apply_user=request.user)
        if MyVotingObj.voting_option.all().count():
            VotingFlag = "false"
            option_obj = MyVotingObj.voting_option.all().first().option
        else:
            VotingFlag = 'true'
            option_obj = ''

        if (now_timestamp - end_timestamp) > 0:
            VotingFlag = "false"

        end_timestamp = int(str_to_timestamp(flow_obj.vote_deadline, '%Y-%m-%d'))
        returnData = {'code': 200, 'message': "success", "VotingOption": VotingOption, "vote_content": vote_content, "voting_flag": 'false' if my_voting.voting_option else "true", "legend_pie": legend_pie,
                      "vote_title": flow_obj.vote_title, "vote_type": flow_obj.vote_type, "id": flow_obj.id, "VotingFlag": VotingFlag, "option_obj": option_obj, "end_timestamp": end_timestamp,
                      "vote_viewable": flow_obj.vote_viewable}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class select_flow(View):
    def post(self, request):
        select_option = json.loads(request.POST.get("select_option", ''))
        flow_id = request.POST.get("flow_id", "")
        obj = request.user.votingpeopletable_set.filter(voting_id__id=int(flow_id)).first()
        for i in select_option:
            option_obj = VotingOptionTable.objects.get(id=int(i))
            obj.voting_option.add(option_obj)
        obj.update_time = datetime.datetime.now()
        obj.save()
        returnDict = {'status': 'success', "message": "success"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DocumentReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'forum/DocumentReport.html', {'realname': real_name, 'position': position, 'department': department})

class VotingStatistics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        letter_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        objs = VotingMasterTable.objects.filter(apply_user=request.user).order_by("-create_time")
        data_list = []
        for obj in range(len(objs)):
            flag = False
            if obj == 0:
                flag = True
            data_list.append({"id": objs[obj].id, "vote_title": objs[obj].vote_title, "flag": flag, "new_flag": False})

        OptionObj = objs.first().votingoptiontable_set.all() if objs else []
        VotingOption, option_dict, legend_pie = [], {}, []
        for option in range(len(OptionObj)):
            VotingOption.append({"serial": letter_list[option], "id": OptionObj[option].id, "option": OptionObj[option].option})
            option_dict[OptionObj[option].option] = letter_list[option]

            legend_pie.append({"value": VotingPeopleTable.objects.filter(voting_option=OptionObj[option]).count(), "name": OptionObj[option].option})

        PeopleObj = objs.first().votingpeopletable_set.all() if objs else []
        PeopleList, voted_number = [], 0
        for people in PeopleObj:
            option_list = [option_dict[i.option] for i in people.voting_option.all()]
            if option_list:
                voted_number += 1
            PeopleList.append({"option": ", ".join(option_list), "real_name": people.apply_user.real_name, "voting_time": people.update_time.strftime("%Y-%m-%d %H:%M") if option_list else ""})

        return render(request, 'forum/VotingStatistics.html', {'realname': real_name, 'position': position, 'department': department, "objs": data_list, "flow_obj": objs.first() if objs else '',
                    "VotingOption": VotingOption, "PeopleList": PeopleList, "voted_number": voted_number, "vote_number": len(PeopleList), "legend_pie": legend_pie})

    def post(self, request):
        letter_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        flow_id = request.POST.get("flow_id", '')
        flow_obj = VotingMasterTable.objects.get(id=flow_id)

        OptionObj = flow_obj.votingoptiontable_set.all()
        VotingOption, option_dict, legend_pie = [], {}, []
        for option in range(len(OptionObj)):
            VotingOption.append({"serial": letter_list[option], "id": OptionObj[option].id, "option": OptionObj[option].option})
            option_dict[OptionObj[option].option] = letter_list[option]

            legend_pie.append({"value": VotingPeopleTable.objects.filter(voting_option=OptionObj[option]).count(), "name": OptionObj[option].option})
        vote_content = flow_obj.vote_content

        PeopleObj = flow_obj.votingpeopletable_set.all()
        PeopleList, voted_number = [], 0
        for people in PeopleObj:
            option_list = [option_dict[i.option] for i in people.voting_option.all()]
            if option_list:
                voted_number += 1
            PeopleList.append({"option": ", ".join(option_list), "real_name": people.apply_user.real_name, "voting_time": people.update_time.strftime("%Y-%m-%d %H:%M") if option_list else ""})

        returnData = {'code': 200, 'message': "success", "VotingOption": VotingOption, "vote_content": vote_content, "legend_pie": legend_pie,
                      "vote_title": flow_obj.vote_title, "id": flow_obj.id, "PeopleList": PeopleList, "voted_number": voted_number, "vote_number": len(PeopleList)}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SurveyQuestionnaire(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        flow_id = request.GET.get("id", '')

        # **************************************************** 查询跟当前人相关的调研流程 ****************************************************
        obj_list = request.user.questionnairepeople_set.all().order_by("-create_time")
        left_list, id_list, ParentId, obj = [], [], '', ''
        for i in obj_list:
            if i.parent_id.id not in id_list:
                survey = 'false'
                RecordObj = QuestionnaireRecord.objects.filter(parent_id=i.survey_id)
                if not RecordObj.count():           # 判断是否已参与调研
                    survey = 'true'
                    if not ParentId and not flow_id:
                        ParentId = i.parent_id.id
                left_list.append({"id": str(i.parent_id.id), "title": i.parent_id.title, "survey": survey})
                id_list.append(i.parent_id.id)

        option_json = []
        if flow_id:
            ParentId = flow_id

        if not flow_id:
            flow_id = ParentId

        if ParentId:
            obj_flag = True
            obj = QuestionnaireTable.objects.get(id=ParentId)
        else:
            if obj_list.count():
                obj_flag = True
                obj = QuestionnaireTable.objects.get(id=obj_list.first().parent_id.id)
            else:
                obj_flag = False
                obj = None
        if obj:
            Serial = 1
            TitleObj = QuestionnaireTitle.objects.filter(survey_id=obj)
            for i in TitleObj:
                OptionObj = QuestionnaireQuestions.objects.filter(survey_id=i)
                RecordObjs = QuestionnaireRecord.objects.filter(parent_id=i, apply_user=request.user)
                OptionList = []
                for j in OptionObj:
                    one_dict = {"id": j.id, "option": j.option,
                                "checked": ("true" if RecordObjs.count() and str(j.id) in RecordObjs.first().illustrate else "false") if i.option_type != "c" else "false",
                                "text": RecordObjs.first().illustrate if RecordObjs.count() and i.option_type == "c" else ""}
                    OptionList.append(one_dict)
                option_json.append({"title": i.survey_title, "type": i.option_type, "Serial": Serial, "id": i.id, "option": OptionList})
                Serial += 1
        return render(request, 'forum/SurveyQuestionnaire.html', {'realname': real_name, 'position': position, 'department': department, 'left_list': left_list,
                                                                  "obj_flag": obj_flag, "obj": obj, "option_json": option_json, "flow_id": flow_id})

    def post(self, request):
        option_list = request.POST.get("option_list", '')
        RecordObjs = QuestionnaireRecord.objects.filter(parent_id=json.loads(option_list)[0]["id"], apply_user=request.user)
        if RecordObjs.count():
            returnData = {'code': 400, 'message': "已参与调研，无需重复提交！", "data": []}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        for io in json.loads(option_list):
            objs = QuestionnaireTitle.objects.get(id=int(io["id"]))
            QuestionnaireRecord.objects.create(parent_id=objs, apply_user=request.user, illustrate=io["option"])
        returnData = {'code': 200, 'message': "success", "data": []}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ResearchStatistics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        flow_id = request.GET.get("id", '')

        # **************************************************** 查询跟当前人相关的调研流程 ****************************************************
        obj_list = QuestionnaireTable.objects.filter(apply_user=request.user).order_by("-create_time")
        left_list, id_list, ParentId, obj = [], [], '', ''
        for i in range(obj_list.count()):
            survey = 'false'
            if i == 0:
                survey = 'true'
                ParentId = obj_list[i].id
            left_list.append({"id": str(obj_list[i].id), "title": obj_list[i].title, "survey": survey})
            id_list.append(obj_list[i].id)

        if not flow_id:
            flow_id = ParentId

        currt_obj = QuestionnaireTable.objects.get(id=flow_id)
        table_list = []

        title_obj = currt_obj.questionnairetitle_set.all()
        title_list = []
        aaaa = 1
        for title in title_obj:
            title_list.append(title.survey_title)               # 小标题列表
            table_dict = {}
            option_obj = title.questionnairequestions_set.all()
            choose_obj = title.questionnairerecord_set.all()
            option_list, number_list = [], []
            for t in option_obj:
                shoose_number = 0
                for j in choose_obj:
                    if str(t.id) in j.illustrate:
                        shoose_number += 1
                option_list.append(t.option)
                number_list.append(shoose_number)

            table_dict["id"] = f"echert_{aaaa}"
            table_dict["subtitle"] = title.survey_title
            table_dict["option_list"] = option_list
            table_dict["number_list"] = number_list
            table_list.append(table_dict)
            aaaa += 1

        obj_flag = False
        if obj_list.count():
            obj_flag = True
        return render(request, 'forum/ResearchStatistics.html', {'realname': real_name, 'position': position, 'department': department, 'left_list': left_list, "flow_id": flow_id,
                                                                 'title': currt_obj.title, "table_list": table_list, "obj_flag": obj_flag})


class confirm_summit(View):
    def post(self, request):
        start_time = request.POST.get("start_time", '')
        end_time = request.POST.get("end_time", '')

        status_dict = {"draft": "拒绝", "audit": "同意", "unaudit": "待审核", "referral": "转审", "shelve": "搁置"}
        node_dict = {'C/D': '科室负责人', 'B': '分管领导意见', 'ys': '院长授权', 'YB': '院办主任', 'YZ': '书记/院长', 'sjk': '审计科审核意见', 'BGS': '党政办审核盖章', 'stb': '审计科转办公室', 'END': '党政办审核盖章'}

        objs = SealApply.objects.filter(state="five", create_time__range=[start_time, end_time])
        all_data = []
        for i in objs:
            ApproveDict = {}
            for j in i.sealapplyauditrecord_set.all().order_by("update_time"):
                if j.node not in ApproveDict:
                    ApproveDict[j.node] = {
                        "data": [{"process_time": j.update_time.strftime("%Y-%m-%d %H:%M"), "process_people": j.audit_people.real_name, "process_state": status_dict[j.state],
                                  "process_opinion": j.audit_note, "signature_picture": '/media/' + str(j.audit_people.signature_picture) if j.audit_people.signature_picture else ''}],
                        "node_name": node_dict[j.node]
                    }
                else:
                    ApproveDict[j.node]["data"].append(
                        {"process_time": j.update_time.strftime("%Y-%m-%d %H:%M"), "process_people": j.audit_people.real_name, "process_state": status_dict[j.state],
                         "process_opinion": j.audit_note, "signature_picture": '/media/' + str(j.audit_people.signature_picture) if j.audit_people.signature_picture else ''}
                    )
            fujian_list = [os.getcwd() + str(h.pdf_path) for h in Topicsattachments.objects.filter(topics_number=i.fj_number, is_deleted=False)]
            all_data.append({"ApproveDict": ApproveDict,
                             "apply_user": i.apply_user.real_name,  # 申请人
                             "create_time": i.create_time.strftime("%Y-%m-%d %H:%M"),  # 申请时间
                             "matter_type_text": i.matter_type_text,  # 申请事由
                             "servings": i.servings,  # 用印次数
                             "number": i.number,  # 用印编号
                             "seal_name": i.seal_name,  # 用印名称
                             "note": i.note, "fujian_list": fujian_list})
        output_filename = SummaryApprovalDocuments().CreateWordTable(all_data, f"{start_time.replace('-', '')}-{end_time.replace('-', '')}")
        returnData = {'code': 200, 'message': "success", "data": all_data, "output_filename": output_filename.replace(os.getcwd(), "")}
        return HttpResponse(json.dumps(returnData), content_type="application/json")
